package com.xmut.xmutbackend.controller;

import com.xmut.xmutbackend.entity.AIRequest;
import com.xmut.xmutbackend.service.AIService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.Map;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    private final AIService aiService;

    public AIController(AIService aiService) {
        this.aiService = aiService;
    }

    @PostMapping("/chat")
    public Mono<ResponseEntity<Map<String, Object>>> chat(@RequestBody AIRequest request) {
        String question = request.getQuestion();
        String conversationId = request.getConversationId();

        return aiService.chat(question, conversationId)
                .map(response -> ResponseEntity.ok(Map.of(
                        "success", true,
                        "data", response
                )))
                .onErrorResume(e -> {
                    int code = e instanceof AIService.AIException ?
                            ((AIService.AIException) e).getStatusCode() : 500;
                    return Mono.just(ResponseEntity.status(code).body(Map.of(
                            "success", false,
                            "error", e.getMessage(),
                            "code", code
                    )));
                });
    }
}
